# -*- coding: utf-8 -*
__author__ = 'dell'
from operator import itemgetter, attrgetter
import MySQLdb

def ship_state_decide(ship_speed,max_speed): #########根据速度判断船舶航行状态
    ship_state = 0
    if ship_speed<1:
        ship_state =1 #######表示'anchorage'
    elif ship_speed>=1 and ship_speed<=3:
        ship_state =2   ###########表示'reach_port'
    elif ship_speed>3 and ship_speed<=max_speed*0.2:
        ship_state =3   #####表示'dynamic_state'
    elif ship_speed>max_speed*0.2 and ship_speed<=max_speed*0.65:
        ship_state =4   #######表示'deceleration_sailing'
    else:ship_state =5  #######表示'cruising_state'
    return  ship_state

def calEmission(cur,time,ship_type,ship_speed,max_speed,max_power,amr,
                efa_pm10,efa_pm2_5,efa_nox,efa_sox,efbi_pm10,efbi_pm2_5,efbi_nox,efbi_sox,efi_pm10,efi_pm_2_5,efi_nox,efi_sox): ######计算四种污染物的排放量
    ship_state =  ship_state_decide(ship_speed,max_speed)
    b_energy = cur.fetchmany(cur.execute("select * from b_energy where ship_type='%s'" %ship_type))[0][ship_state]
    lf = (float(ship_speed)/float(max_speed))**3
    lf_temp = min(20,int(round(lf*100)))  ########用于计算cf
    [lf_temp,cf_pm10,cf_pm2_5,cf_nox,cf_sox] = list(cur.fetchmany(cur.execute("select * from cf where lf=%d" %lf_temp))[0])
    lf_a = cur.fetchmany(cur.execute("select * from lf_a where ship_type='%s'" %ship_type))[0][ship_state]
    main_engine = cur.fetchmany(cur.execute("select * from worktime_state where machine='main_engine'"))[0][ship_state]
    auxiliary_engine = cur.fetchmany(cur.execute("select * from worktime_state where machine='auxiliary_engine'" ))[0][ship_state]
    boiler = cur.fetchmany(cur.execute("select * from worktime_state where machine='boiler'" ))[0][ship_state]
    mcr = max_power
    a_mcr = mcr*amr
    efa = [efa_pm10,efa_pm2_5,efa_nox,efa_sox]
    efbi = [efbi_pm10,efbi_pm2_5,efbi_nox,efbi_sox]
    efi = [efi_pm10,efi_pm_2_5,efi_nox,efi_sox]
    cf = [cf_pm10,cf_pm2_5,cf_nox,cf_sox]
    emission =[]
    for i in range(4):
        main_engine_emission = float(mcr)*float(lf)*float(efi[i])*float(cf[i])*time*main_engine
        auxiliary_engine_mission = float(a_mcr)*float(lf_a)*float(efa[i])*time*auxiliary_engine
        boiler_mission = float(b_energy)*float(efbi[i])*time*boiler
        emission.append(main_engine_emission+auxiliary_engine_mission+boiler_mission)
    return emission